#pragma once

#include "NetworkMessage.h"
#include <memory>
#include <functional>
#include <unordered_map>
#include <mutex>

namespace SeanNetwork {

/**
 * @brief Interface for message handling operations.
 * 
 * Separates message processing logic from transport logic,
 * allowing for different message handling strategies.
 */
class IMessageHandler {
public:
    virtual ~IMessageHandler() = default;
    
    /**
     * Process an incoming message.
     * 
     * @param message The network message to process
     * @return True if message was processed successfully, false otherwise
     */
    virtual bool ProcessMessage(std::shared_ptr<NetworkMessage> message) = 0;
    
    /**
     * Register a message-specific handler.
     * 
     * @param messageId The ID of the message to handle
     * @param handler The function to call when a message with this ID is received
     */
    virtual void RegisterHandler(uint32_t messageId, 
        std::function<void(std::shared_ptr<NetworkMessage>)> handler) = 0;
    
    /**
     * Unregister a message handler.
     * 
     * @param messageId The message ID to unregister
     */
    virtual void UnregisterHandler(uint32_t messageId) = 0;
};

/**
 * @brief Default implementation of the IMessageHandler interface.
 */
class DefaultMessageHandler : public IMessageHandler {
public:
    DefaultMessageHandler();
    ~DefaultMessageHandler() override;
    
    bool ProcessMessage(std::shared_ptr<NetworkMessage> message) override;
    void RegisterHandler(uint32_t messageId, 
        std::function<void(std::shared_ptr<NetworkMessage>)> handler) override;
    void UnregisterHandler(uint32_t messageId) override;
    
private:
    // Map of message ID to handler function
    std::unordered_map<uint32_t, std::function<void(std::shared_ptr<NetworkMessage>)>> m_Handlers;
    
    // Default handler for unregistered message IDs
    std::function<void(std::shared_ptr<NetworkMessage>)> m_DefaultHandler;
    
    // Mutex for thread safety
    std::mutex m_HandlerMutex;
};

} // namespace SeanNetwork 
